#encoding:utf-8
from tornado.log import access_log as logger

from pojo.entity.BaseEntity import BaseEntity
from pojo.entity import Constant
import Settings
from utils import reqParamUtil

class Order(BaseEntity):
    id=None
    strategyId=None
    userId=None
    sender=None #订单操作类型。00：策略下单；01：人工下单；02：高送配；03：退市
    sendErrDesc=None #订单发送错误描述 "全部成交","部分成交","涨停一字板","跌停一字板","停牌",""余额不足"
    sendErrCode=None #订单发送错误描述 "全部成交","部分成交","涨停一字板","跌停一字板","停牌",""余额不足"
    tradeDate=None #交易日

    orderDate=None #委托日期 yyyy-MM-dd HH:mm:ss.SSSSSS
    userCode=None
    account=None
    branchNo=None
    secuAccount=None

    market=None #包含板块 char(2)
    symbol=None
    tradeType=None #交易行为定义
    price=None
    vol=None

    seat=None #交易席位
    orderId=None #合同序号

    orderAmount=None #委托金额
    orderFrozenAmount=None #委托冻结金额

    matchedDate=None#交易日期 yyyy-MM-dd
    sename=None #证券名称
    matchedVol = None  # 成交数量
    matchedAmount = None  # 成交金额
    matchedPrice = None  # 成交价格
    withDrawVol = None  # 已撤数量
    tradeId=None #tradeId

    isWithDraw=None #撤单标志 CHAR(1) 0：正常委托；1:撤单委托
    isWithDrawn=None #已撤单标志 CHAR(1)  0:未撤单；1:已撤单
    sendFlag=None #发送标志0：未发送 1：已发送
    validFlag=None #合法标志char(1) 0：非法 1：合法
    canWithDraw=None #可撤标志 1:允许撤单 0：不允许撤单

    status=None #订单状态。0：所有委托，1：可撤委托；2：已成交委托；3：非法委托

    entryTime = None  # 更新时间  yyyy-MM-dd HH:mm:ss:SSS

    def isSendSuccess(self):
        return self.orderId is not None

    def isMatched(self):
        return self.matchedVol is not None and self.vol == self.matchedVol

    def isCanceled(self):
        """是否已撤单"""
        return self.isWithDrawn==u"1" and self.vol==self.withDrawVol

    def canCancel(self):
        startTime = Settings.CAN_WITHDRAW_STARTTIME
        endTime = Settings.CAN_WITHDRAW_ENDTIME
        curTime = reqParamUtil.getCurrentTime()
        canCancelFlag=self.canWithDraw==u"1"
        logger.debug(
                "CanWithDraw:{canWithDraw},curTime:{curTime},CancelStartTime:{start},CancelEndTime:{end}".format(
                    curTime=curTime, start=startTime, end=endTime, canWithDraw=self.canWithDraw))

        return canCancelFlag and curTime > startTime and curTime < endTime

    def setEntryTime(self):
        self.entryTime=reqParamUtil.getEntryTime()

    def getStatusDesc(self):
        descMap={
            None:"",
            Constant.QUERY_ORDERS_MODE_CANCELABLE:"可撤",
            Constant.QUERY_ORDERS_MODE_MATCHED:"已成",
            Constant.QUERY_ORDERS_MODE_INVALID:"非法订单{desc}".format(desc="_"+self.sendErrDesc if self.sendErrDesc is not None else ""),
            Constant.QUERY_ORDERS_MODE_CANCELED:"已撤",
        }
        return descMap.get(self.status)

    def changeFormat(self):
        floatFields=["price","orderAmount","orderFrozenAmount","matchedAmount","matchedPrice"]
        intFields=["vol","matchedVol","withDrawVol"]
        for key,val in self.__dict__.items():
            if key in floatFields:
                self.__dict__[key]=float(val.encode("utf-8"))
            elif key in intFields:
                self.__dict__[key]=int(val.encode("utf-8"))
            else:
                pass
        return self

    def getTableName(self):
        return "real_order"

    def getTableFieldMap(self):
        tableFieldMap={
            "id":"id",
            "strategyId":"strategy_id",
            "userId":"user_id",
            "sender":"sender",
            "sendErrDesc":"send_err_desc",
            "sendErrCode":"send_err_code",
            "tradeDate":"trade_date",
            "orderDate":"order_date",
            "userCode":"user_code",
            "account":"account",
            "branchNo":"branch",
            "secuAccount":"secu_account",
            "market":"market",
            "symbol":"symbol",
            "tradeType":"trade_type",
            "price":"price",
            "vol":"vol",
            "seat":"seat",
            "orderId":"order_id",
            "orderAmount":"order_amount",
            "orderFrozenAmount":"order_frozen_amount",
            "matchedDate":"matched_date",
            "sename":"sename",
            "matchedVol":"matched_vol",
            "matchedAmount":"matched_amount",
            "matchedPrice":"matched_price",
            "withDrawVol":"withdraw_vol",
            "tradeId":"trade_id",
            "isWithDraw":"is_withdraw",
            "isWithDrawn":"is_withdrawn",
            "sendFlag":"send_flag",
            "validFlag":"valid_flag",
            "canWithDraw":"can_withdraw",
            "entryTime":"entry_time",
            "status":"status",
        }
        return tableFieldMap

    def __str__(self):
        descDict = self.__dict__
        return """Order-----{desc}""".format(
            desc=",".join(
                ["{key}:{val}".format(key=key, val=val.encode("utf-8") if isinstance(val, unicode) else val) for
                 key, val in descDict.items()])
        )